#! /bin/sh

if test -d ../fw/bin
  then
    PATH="`pwd`/../fw/bin:$PATH"
    export PATH
  fi

if test -z "$MAKE"
  then
    gmake=`which gmake`

    if test $? = 0 
      then
        MAKE=gmake
      else
        MAKE=make
      fi
  fi

(
set -x
test -h fw.local || ln -sf ../fw.local fw.local || exit 1
test -h share || ln -sf .. share || exit 1
testsdir="`pwd`"
rm -rf megatmp
{ 
  mkdir megatmp &&
  cd megatmp &&
  env FW_ROOT="$testsdir"                               \
  fw-init --name tmp                                    \
          --revision none                               \
          --template "erlang-rebar"      
} || exit 1
cd tmp
rm -f fw
mkdir fw
cwd=`pwd`
mkdir fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-bootstrap` fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-exec` fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-init` fw/bin
cp `env PATH="../../../fw/bin:$PATH" which fw-package` fw/bin
(cd "../../../fw"; find . -print | cpio -pvd "$cwd/fw")
(cd "../../../fw.local"; find template -print | cpio -pvd "$cwd/fw")
(cd "../../../fw.local"; find m4 -print | cpio -pvd "$cwd/fw")

# disable the addition of package providing build type to the BUILD_DEPENDS 
# since it will not be installed at this point
#cp -f "${testsdir}/share/fw/build/automake/load-config" fw/template/"erlang-rebar"/ || \
#exit 1
#chmod +x fw/template/"erlang-rebar"/load-config || exit 1
perl -pi -e 's/^.*fw-template-erlang-rebar.*$//g' fw/template/erlang-rebar/load-config

./bootstrap || exit 1
./build || exit 1
"${MAKE}" -s check || exit 1

if test "@FW_NATIVE_PACKAGE_TYPE@" != none
  then
    "${MAKE}" "package-@FW_NATIVE_PACKAGE_TYPE@" || exit 1
  fi

"${MAKE}" -s maintainer-clean
rm -rf fw
test -z "`find . -name '*.am'`" || exit 1
) > test-template.out 2>&1 || exit 1

rm fw.local
rm share
rm -rf megatmp
rm -rf cvstmp
